import pickle
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from info import Info
from time import sleep

class Kdriver:
    def __init__(self, driver):
        self.driver = driver

    def wait_element_load(self, element, expiration_time=10, **keywargs):
        while not self.is_exist(element, **keywargs):
            expiration_time -= 2
            if expiration_time < 0:
                return False
            sleep(2)
        return True

    def is_exist(self, element, **keywargs):
        flag = True
        try:
            target_element = self.driver.find_element_by_css_selector(element)
            if len(keywargs) > 0:
                for k,v in keywargs.items():
                    if getattr(target_element,k) != v:
                        raise NoSuchElementException
            return flag
        except NoSuchElementException:
            flag = False
        return flag

    def load_cookie(self, cookie):
        self.driver.delete_all_cookies()
        with open(Info.cookie_path, 'rb') as ck:
            cookies = pickle.load(ck)
        for cookie in cookies:
            self.driver.add_cookie(cookie)


def create_driver():
    #这里还需要封装opention
    driver = webdriver.Chrome(executable_path=Info.driver_path)
    kdriver = Kdriver(driver)
    return driver,kdriver
